package org.ztr.yanai.blog.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.ztr.yanai.blog.constant.Constants;
import org.ztr.yanai.blog.utils.JwtUtil;

import java.io.IOException;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/11/22 14:30
 * @Description: JWT认证过滤器，从请求头中提取JWT令牌并验证
 * @Version: 1.0
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired(required = false)
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        // 从请求头中获取Token
        String authHeader = request.getHeader(Constants.Jwt.TOKEN_HEADER);

        if (authHeader != null && authHeader.startsWith(Constants.Jwt.TOKEN_PREFIX)) {
            String token = authHeader.substring(Constants.Jwt.TOKEN_PREFIX.length());

            try {
                // 验证Token
                if (jwtUtil.validateToken(token)) {
                    String username = jwtUtil.getUsernameFromToken(token);

                    // 如果当前SecurityContext中没有认证信息
                    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                        // 加载用户详情（如果配置了UserDetailsService）
                        if (userDetailsService != null) {
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                            // 创建认证对象
                            UsernamePasswordAuthenticationToken authentication =
                                    new UsernamePasswordAuthenticationToken(
                                            userDetails,
                                            null,
                                            userDetails.getAuthorities());
                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                            // 设置到SecurityContext
                            SecurityContextHolder.getContext().setAuthentication(authentication);

                            log.debug("JWT认证成功，用户: {}", username);
                        }
                    }
                } else {
                    log.warn("无效的JWT Token");
                }
            } catch (Exception e) {
                log.error("JWT认证失败: {}", e.getMessage());
            }
        }

        filterChain.doFilter(request, response);
    }
}
